package com.qny.ai.controller;

import com.qny.ai.common.ApiResponse;
import com.qny.ai.dto.user.UserLoginRequest;
import com.qny.ai.dto.user.UserRegisterRequest;
import com.qny.ai.entity.AppUser;
import com.qny.ai.service.UserService;
import com.qny.ai.vo.UserVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @PostMapping("/register")
    public ApiResponse<Long> register(@Valid @RequestBody UserRegisterRequest request) {
        return ApiResponse.ok(userService.register(request));
    }

    @PostMapping("/login")
    public ApiResponse<UserVO> login(@Valid @RequestBody UserLoginRequest request) {
        return ApiResponse.ok(userService.login(request));
    }
    
    @GetMapping("/profile")
    public ApiResponse<UserVO> getProfile(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        return ApiResponse.ok(userService.getCurrentUser(userId));
    }
    
    @PutMapping("/profile")
    public ApiResponse<UserVO> updateProfile(@RequestBody Map<String, String> request, HttpServletRequest httpRequest) {
        Long userId = (Long) httpRequest.getAttribute("userId");
        String username = request.get("username");
        String email = request.get("email");
        return ApiResponse.ok(userService.updateProfile(userId, username, email));
    }
    
    @PostMapping("/change-password")
    public ApiResponse<Boolean> changePassword(@RequestBody Map<String, String> request, HttpServletRequest httpRequest) {
        Long userId = (Long) httpRequest.getAttribute("userId");
        String oldPassword = request.get("currentPassword");
        String newPassword = request.get("newPassword");
        return ApiResponse.ok(userService.changePassword(userId, oldPassword, newPassword));
    }
}


